import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { BleProvider } from '../../providers/ble/ble';
import { ChargstationService } from '../../providers/service/chargstation.service';
import { Network } from '@ionic-native/network';
import { DialogProvider } from '../../providers/dialog/dialog';
import { Device } from '@ionic-native/device';
import { LoadingController, Loading } from 'ionic-angular';
import { ChargDataService } from '../../providers/service/charg-data.service';

// baidu map
declare var BMap;
declare var BMap_Symbol_SHAPE_POINT;
declare var BMap_Symbol_SHAPE_FORWARD_CLOSED_ARROW;

/**
 * Generated class for the NodeListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-node-list',
  templateUrl: 'node-list.html',
})
export class NodeListPage {
  // 经度
  lng = 108.29723356;
  // 纬度
  lat = 22.80649294;
  // 站点
  site: Site[] = new Array<Site>();
  site2: Site[] = new Array<Site>();
  siteFind: Site[] = new Array<Site>();
  //有网状态=1 断网=0
  Internet = 1;

  options = {
    enableHighAccuracy: true,  // 是否使用 GPS
    maximumAge: 30000,         // 缓存时间
    timeout: 27000,            // 超时时间
    coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
  }
  siteone: String;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public http: HttpProvider,
    public chargstation: ChargstationService,
    private network: Network,
    public ble: BleProvider,
    public dialog: DialogProvider,
    public cordova_plugin_device: Device,
    public loadingCtrl: LoadingController,
    public chargdata: ChargDataService,
  ) {
  }

  async ionViewDidLoad() {
    console.log('ionViewDidLoad NodeListPage');
    if (this.network.type !== 'none' && this.network.type !== '2g') {
      this.getPoint();
      // this.getLatitudecpile()
      // this.dialog.showAlert('getPoint', JSON.stringify(this.site2.length));
      this.Internet = 1;
      // this.getLatitudecpile();
      this.ble.scan(0);
      this.site = this.navParams.get('data');
    }
    if (this.network.type === 'none' || this.network.type === '2g') {
      this.Internet = 0
      let a = await this.chargstation.find((site) => site.key !== '');
      let chargdata = await this.chargdata.find((chargdata) => chargdata.key !== '');
      for(let s of a){
        s.frequencyOfUse = 0;
        }
      for(let s of a){
        for(let c of chargdata) {
        if(s.charging_pile_id === c.q_charging_pile.charging_pile_id) {
          s.frequencyOfUse += 1
        }
        }
      }	
      a.sort(
        function (a, b) {
          return b.frequencyOfUse - a.frequencyOfUse
        }
      )
      this.ble.scan(0);
      this.site = a;
      this.site2 = a;
    }
  }

  skipToChargingBattery(site) {
    if (site.charging_unit_List.length > 0) {
      this.navCtrl.push('DeviceSelectPage', { data: site });
    }
  }



  near() {
    this.navCtrl.push('NearPage')
  }

  //本页查找
  async search() {
    this.siteFind.splice(0);//数组清零
    /*
    indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
    如果未在此实例中找到该字符或字符串，则此方法返回 -1。
    */
    for (var i = 0; i < this.site2.length; i++) {
      if (this.site2[i].charging_pile_name.indexOf(this.siteone) >= 0) {
        await this.siteFind.push(this.site2[i]);
      }
    }

  }


  // 计算查询点的经纬度范围
  rangeCalculation(longitude, latitude) {
    //先计算查询点的经纬度范围
    const r = 6371;//地球半径千米
    const dis = 10;//10千米距离
    let dlng = 2 * Math.asin(Math.sin(dis / (2 * r)) / Math.cos(latitude * Math.PI / 180));
    dlng = dlng * 180 / Math.PI;//角度转为弧度
    let dlat = dis / r;
    dlat = dlat * 180 / Math.PI;
    const range = {
      minlat: latitude - dlat,
      maxlat: latitude + dlat,
      minlng: longitude - dlng,
      maxlng: longitude + dlng,
    }

    return range;
  }

  // 获得附近充电桩
  async getLatitudecpile() {
    let loading = this.loadingCtrl.create({
      content: '搜索中...'//数据加载中显示
    });
    loading.present();
    let loadingSign = 1;
    await this.http.postJson('', 'device/chargingp/latitudecpile', this.rangeCalculation(this.lng, this.lat), '')
      .then(res => {
        // console.log('res')
        // console.log(res)

        if (res['status'] == 200) {
          // this.site = res['data'];
          var map = new BMap.Map("allmap");
          this.site2.splice(0);
          this.site = res['data'];
          for (var i = 0; i < this.site.length; i++) {
            if (this.site[i].charging_unit_List.length > 0) {
              // var c = this.site[i].charging_unit_List;
              var pointA = new BMap.Point(this.lng, this.lat);  // 创建点坐标A
              var pointB = new BMap.Point(this.site[i].longitude, this.site[i].latitude);  // 创建点坐标B
              // this.dialog.showAlert('getLatitudecpile', JSON.stringify(this.site2[0]));
              // return map.getDistance(pointA,pointB);
              this.site[i].distance = map.getDistance(pointA, pointB);
              this.site2.push(this.site[i]);
            } 
          }
          this.site2.sort(
            function (a, b) {
              return a.distance - b.distance
            }
          )
          loadingSign = 0;
          loading.dismiss();
          this.chargstation.deleteAll();
          for (var j = 0; j < this.site2.length; j++) {
            this.chargstation.save(this.site2[j]);
          }
        } else {
          loadingSign = 0;
          loading.dismiss();
        }
      });
      const this_ = this;
      setTimeout(
        function() {
          if(loadingSign === 1) {
            loading.dismiss();
            this_.dialog.showConfirm('搜索失败，点击确定后重试', '').then(success => {
              this_.getLatitudecpile();
            },
            fail => {

            })
          }      
        }
        ,5000)
  }


  getPoint() {
    navigator.geolocation.getCurrentPosition((success) => {
      this.lng = success['coords']['longitude'];
      this.lat = success['coords']['latitude'];


      if (this.cordova_plugin_device.platform === 'iOS') {
        var ggPoint = new BMap.Point(this.lng, this.lat);

        var convertor = new BMap.Convertor();
        var pointArr = [];
        pointArr.push(ggPoint);

        convertor.translate(pointArr, 1, 5, (data) => {
          this.lng = data.points[0].lng;
          this.lat = data.points[0].lat;
          this.getLatitudecpile();
        })

      }


      if (this.cordova_plugin_device.platform === 'Android') {
        this.getLatitudecpile();

      }

    },
      (error) => {
        this.dialog.showAlert('提示', '无法获取当前位置');
        this.lng = 108.282742;
        this.lat = 22.880928;
        this.getLatitudecpile();
      }
      , this.options);



  }


  /**   
   * 通过经纬度获取距离(单位：米)
   * @param lat1   
   * @param lng1   
   * @param lat2   
   * @param lng2   
   * @return   
   */
  getDistance(lng1, lat1, lng2, lat2) {
    // const EARTH_RADIUS = 6378.137;
    // const radLat1 = lat1 * Math.PI / 180.0;
    // const radLat2 = lat2 * Math.PI / 180.0;
    // const a = radLat1 - radLat2;
    // const b = (lng1 * Math.PI / 180.0) - (lng2 * Math.PI / 180.0);
    // let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
    //   + Math.cos(radLat1) * Math.cos(radLat2)
    //   * Math.pow(Math.sin(b / 2), 2)));
    // s = s * EARTH_RADIUS;
    // s = Math.round(s * 10000) / 10000;
    // s = s * 1000;
    // if (s) {
    //   return s;
    // } else { return 0; }

  }

}

export class Site {
  charging_pile_name: any;
  cell_name: any;
  map_positioning: any;
  coordinate_info: any;
  address: any;
  supplementary_info: any;
  delivery_time: any;
  ammeter_code: any;
  province: any;
  city: any;
  area: any;
  charging_pile_id: any;
  business_subjec_name: any;
  property_company_name: any;
  charging_unit_List: any[];
  charge_uprice_List: any[];
  latitude: any;
  longitude: any;
  distance: any;
}